<template>
  <el-card class="w-full pt-[5px] pb0">
    <CheckType v-model="searchForm.checkState" @typeChange="handleSearch" :countMap="countMap" />
    <el-form :model="searchForm" class="mt-[20px]" label-width="96px" ref="searchFormRef">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="searchForm.name" placeholder="项目名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="申请人" prop="applierName">
            <el-input v-model="searchForm.applierName" placeholder="申请人" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="" label-width="0">
            <el-input
              v-model="searchForm.minFee"
              placeholder="最小项目总经费"
              clearable
              style="width: calc(50% - 10px)"
              @input="fomateNumber(searchForm, 'minFee', $event)"
            />
            <span style="width: 20px; text-align: center">至</span>
            <el-input
              v-model="searchForm.maxFee"
              placeholder="最大项目总经费"
              clearable
              style="width: calc(50% - 10px)"
              class="mb-[0px]"
              @input="fomateNumber(searchForm, 'maxFee', $event)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <div class="flex justify-end">
            <el-button type="primary" @click="searchFormOpen = !searchFormOpen"
              >更多
              <el-icon color="#fff">
                <CaretTop v-show="searchFormOpen" />
                <CaretBottom v-show="!searchFormOpen" />
              </el-icon>
            </el-button>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-show="searchFormOpen">
        <el-col :span="6">
          <el-form-item label="申请日期">
            <el-date-picker
              v-model="searchForm.applyDate1"
              type="year"
              value-format="YYYY"
              style="width: calc(50% - 10px)"
            />
            <span style="width: 20px; text-align: center">至</span>
            <el-date-picker
              v-model="searchForm.applyDate2"
              type="year"
              value-format="YYYY"
              style="width: calc(50% - 10px)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="立项状态" prop="lixiangState">
            <CustomTreeSelect
              :isFetch="false"
              :dataList="lxStatusList"
              placeholder="立项状态"
              v-model="searchForm.lixiangState"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属单位" prop="unitId">
            <CustomTreeSelect
              :dataList="unitList"
              placeholder="所属单位"
              v-model="searchForm.unitId"
              valueKey="codeColumn"
              labelKey="valueColumn"
              :isFetch="false"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目编号" prop="projectCode">
            <el-input v-model="searchForm.projectCode" placeholder="项目编号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="一级学科" prop="l1Code">
            <CustomTreeSelect
              paramsName="一级学科"
              placeholder="一级学科"
              v-model="searchForm.l1Code"
              valueKey="id"
              labelKey="label"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="关键词" prop="keyWord">
            <el-input v-model="searchForm.keyWord" placeholder="关键词" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="审核状态" prop="checkStateList">
            <CustomTreeSelect
              placeholder="审核状态"
              v-model="searchForm.checkStateList"
              valueKey="dictValue"
              labelKey="dictLabel"
              :isFetch="false"
              :dataList="checkStatusList"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <el-card class="w-full pt-[5px] mt-[10px]">
    <div class="mb-[20px]">
      <el-button @click="handleDelSelect">
        <el-icon class="mr-[5px]"><DeleteFilled /></el-icon>
        删除
      </el-button>
      <el-button @click="handleExport">
        <svg-icon iconClass="export" class="mr-[5px]"></svg-icon>导出
      </el-button>
    </div>
    <el-table
      :data="tableData"
      class="w-full"
      stripe
      row-key="id"
      v-loading="loading"
      ref="tableRef"
    >
      <el-table-column
        type="selection"
        width="40"
        :selectable="(row) => row.checkState != 1 && row.checkState != 2"
      />
      <el-table-column label="项目名称">
        <template #default="{ row }">
          <el-link type="primary" @click="handleShow(row.id)">{{ row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="申请人" width="90">
        <template #default="{ row }">
          <el-link type="primary" @click="handleViewPerson(row.applierId)" v-if="row.applierId">{{
            row.applyierName
          }}</el-link>
          <span v-else>{{ row.applyierName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="applyFee" label="申请经费（万元）" width="95"/>
      <el-table-column label="申请日期" width="100">
        <template #default="{ row }">
          <DateLabel :value="row.applyDate" />
        </template>
      </el-table-column>
      <el-table-column label="立项状态" width="90">
        <template #default="{ row }">
          <CommonLabel :dataList="lxStatusList" :value="row.lixiangState" />
        </template>
      </el-table-column>
      <el-table-column label="所属单位" width="120">
        <template #default="{ row }">
          <CommonTreeLabel
            :dataList="unitList"
            valueKey="codeColumn"
            labelKey="valueColumn"
            :value="row.unitId"
          />
        </template>
      </el-table-column>
      <el-table-column label="审核状态"  width="100">
        <template #default="{ row }">
          <CommonLabel
            :dataList="checkStatusList"
            valueKey="dictValue"
            labelKey="dictLabel"
            :value="row.checkState"
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="260" align="center">
        <template #default="{ row }">
          <div class="mb-[10px] flex">
            <template v-if="[-1, 1, 3].includes(Number(row.checkState))">
              <el-button
                type="primary"
                size="small"
                plain
                @click="handleEdit(row.id, row.isAuditor, row.taskId, row.checkState)"
              >
                编辑
              </el-button>
            </template>
            <template v-if="[-1, 3].includes(Number(row.checkState))">
              <el-button type="danger" size="small" plain @click="handleDel(row.id)"
                >删除</el-button
              >
            </template>
            <el-button
              type="success"
              size="small"
              plain
              @click="handleCheck(row.id, row.processInstanceId)"
              v-if="row.isAuditor"
              >审核</el-button
            >
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleLx(row.id, 2)"
              v-if="
                row.isReview === '0' && row.lixiangState === '0' && Number(row.checkState) === 2
              "
            >
              批准立项
            </el-button>
            <el-button
              type="warning"
              size="small"
              plain
              @click="handleLx(row.id, 0)"
              v-if="
                row.isReview === '0' && row.lixiangState === '2' && Number(row.checkState) === 2
              "
            >
              撤销立项
            </el-button>
          </div>
          <div class="flex">
            <el-button type="primary" size="small" plain @click="handleProject(row.applierId)">
              负责人已参与项目
            </el-button>
            <el-button type="primary" size="small" plain @click="downFiles(row.fileInfo)">
              打印申报书
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-[20px] flex justify-end">
      <el-pagination
        v-bind="pagination"
        @update:current-page="currentChange"
        @update:page-size="sizeChange"
      />
    </div>
  </el-card>
  <EditModal ref="editModalRef" @edit-success="handleSearch" v-if="editModalVisible" />
  <ViewModal ref="viewModalRef" v-if="viewModalVisible" />
  <CheckModal ref="checkModalRef" v-if="checkModalVisible" @check-success="handleSearch" />
  <HistoryJoinModal ref="historyJoinModalRef" />
  <FileDownList ref="fileDownListRef" />
  <PersonView ref="personViewModalRef" />
  <exportModal
    v-model="exportVisible"
    :selectList="exportFieldList"
    :title="exportTitle"
    @callBack="handleSelectOk"
  />
</template>

<script setup>
import useTable from "@/hooks/useTable";
import CheckType from "@/views/project/components/CheckType.vue";
import EditModal from "./components/EditModal.vue";
import CheckModal from "./components/CheckModal.vue";
import exportModal from "@/components/export";
import ViewModal from "@/views/project/xj/sbxm/sbcl/components/ViewModal.vue";
import FileDownList from "@/views/project/components/FileDownList.vue";
import HistoryJoinModal from "@/views/project/xj/sbxm/index/components/HistoryJoinModal.vue";
import { handleDownload, downloadFile, fomateNumber } from "@/utils/main";
import {
  getList,
  delRecords,
  exportFields,
  exportRecords,
  getCount,
} from "@/api/project/xj/sbxm/sbcl";
import { changeLxType } from "@/api/project/xj/xmps/psxm";
import DateLabel from "@/views/project/components/DateLabel.vue";
import CustomTreeSelect from "@/views/project/components/CustomTreeSelect.vue";
import CommonTreeLabel from "@/views/project/components/CommonTreeLabel.vue";
import CommonLabel from "@/views/project/components/CommonLabel.vue";
import PersonView from "@/views/project/components/PersonView.vue";
import { useRoute } from "vue-router";
import useCommonFetch from "@/hooks/useCommonFetch";
import useDictFetch from "@/hooks/useDictFetch";
import { ElMessageBox, ElMessage } from "element-plus";
const unitList = useCommonFetch("成果归属单位");
const lxStatusList = useCommonFetch("立项状态");
const checkStatusList = useDictFetch("bpm_process_instance_status"); //审核状态
const route = useRoute();
const id = route.query.id;
const searchFormOpen = ref(false);
const searchFormRef = ref();
const editModalRef = ref();
const editModalVisible = ref(false);
const checkModalRef = ref();
const checkModalVisible = ref(false);
const viewModalRef = ref();
const viewModalVisible = ref(false);
const historyJoinModalRef = ref();
const tableRef = ref();
const exportVisible = ref(false);
const exportFieldList = ref([]);
const fileDownListRef = ref(false);
const personViewModalRef = ref();
const exportTitle = "基本科研业务费项目申报材料";
const countMap = ref({
  total: 0,
  1: 0,
  2: 0,
  3: 0,
});
const searchForm = ref({
  checkState: "",
  name: "",
  applierName: "",
  minFee: "",
  maxFee: "",
  applyDate1: "", //申请时间
  applyDate2: "",
  lixiangState: [], //立项状态
  unitId: [], //所属单位
  projectCode: "", //项目编号
  l1Code: [], //一级学科
  keyWord: "",
  checkStateList: [], //审核状态
});
const { loading, pagination, sizeChange, currentChange, tableData, handleDelete, search } =
  useTable(
    (pagin) =>
      getList({
        pageNum: pagin.pageNum,
        pageSize: pagin.pageSize,
        infoId: id,
        ...searchForm.value,
      }),
    { getCountStatistics }
  );
getCountStatistics();
//点击编辑
const handleEdit = (id, isAuditor, taskId, checkStatus) => {
  editModalVisible.value = true;
  nextTick(() => {
    editModalRef.value.edit(id, isAuditor, taskId, checkStatus);
  });
};
//点击名称查看
const handleShow = (id) => {
  viewModalVisible.value = true;
  nextTick(() => {
    viewModalRef.value.view(id);
  });
};
//点击人员姓名
const handleViewPerson = (id) => {
  personViewModalRef.value.view(id);
};
//点击历史参与项目
const handleProject = (applierId) => {
  historyJoinModalRef.value.view(applierId);
};
//点击删除
const handleDel = (id) => {
  const params = {
    ids: [id],
  };
  handleDelete(delRecords, params);
};
//批量删除
const handleDelSelect = () => {
  //获取当前选中行
  const selectRows = tableRef.value.getSelectionRows();
  if (!selectRows.length) {
    ElMessage({
      message: "请选择要删除的数据！",
      type: "warning",
    });
    return;
  }
  const ids = selectRows.map((item) => item.id);
  const params = {
    ids,
  };
  handleDelete(delRecords, params);
};
//点击审核
const handleCheck = (id, processId) => {
  checkModalVisible.value = true;
  nextTick(() => {
    checkModalRef.value.check(id, processId);
  });
};
//立项
const handleLx = async (bookId, status) => {
  const message =
    status == 2
      ? "确定要批准立项吗？"
      : "撤销立项后将同时删除已立项项目，无法恢复！确定要撤销立项吗？";
  try {
    ElMessageBox.confirm(message, "提示", {
      type: "warning",
    }).then(async () => {
      const params = {
        bookId,
        projectState: status, //2 立项  0取消立项
      };
      const res = await changeLxType(params);
      if (res.code == 200) {
        ElMessage({
          message: "操作成功！",
          type: "success",
        });
        handleSearch();
      }
    });
  } catch (error) {
    console.log(error);
  }
};
//获取导出字段
const getExportFileds = async () => {
  try {
    const params = {
      page: "review",
    };
    const res = await exportFields(params);
    if (res.code == 200) {
      const defaultCheckedList = [
        "projectCode",
        "projectName",
        "applierName",
        "applyFee",
        "applyDate",
        "projectState",
        "unitName",
        "subject",
      ];
      res.data.forEach((item) => {
        exportFieldList.value.push({
          lable: item.showName,
          value: item.field,
          isSelect: defaultCheckedList.includes(item.field) ? true : false,
        });
      });
    }
  } catch (error) {
    console.log(error);
  }
};
//点击导出按钮
const handleExport = async () => {
  //exportFieldList为空时才获取数据
  if (!exportFieldList.value.length) {
    await getExportFileds();
  }
  exportVisible.value = true;
};
//导出字段选择完毕
const handleSelectOk = async (val) => {
  const cols = val.map((item) => item.prop);
  try {
    const params = {
      ...searchForm.value,
      infoId: id,
      cols,
    };
    const res = await exportRecords(params);
    if (res.type != "application/json") {
      downloadFile(res, exportTitle + ".xlsx");
    }
  } catch (error) {
    console.log(error);
  }
};
//获取检索数量统计
async function getCountStatistics() {
  const params = {
    infoId: id,
    ...searchForm.value,
    checkState: "",
  };
  try {
    const res = await getCount(params);
    countMap.value = {
      total: 0,
      1: 0,
      2: 0,
      3: 0,
    };
    let totalCount = 0;
    res.data.forEach((item) => {
      countMap.value[item.checkState] = item.count;
      totalCount += item.count;
    });
    countMap.value.total = totalCount;
  } catch (error) {
    console.log(error);
  }
}
//点击打印申报数
const downFiles = (fileList) => {
  if (fileList.length > 1) {
    fileDownListRef.value.showList(fileList);
  } else {
    handleDownload(fileList[0].id, fileList[0].fileName);
  }
};
//点击重置
const resetForm = () => {
  searchFormRef.value.resetFields();
  searchForm.value.minFee = "";
  searchForm.value.maxFee = "";
  searchForm.value.applyDate1 = "";
  searchForm.value.applyDate2 = "";
  handleSearch();
};
//执行检索并获取数量统计
const handleSearch = () => {
  search();
  getCountStatistics();
};
</script>

<style scoped lang="scss"></style>
